package com.ssyc.gsk_teacher.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.utils.TextUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.bean.ResultInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.OnloadingMoreListener;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.AlertDialogUtil;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.activity.TeacherEventActivity;
import com.ssyc.gsk_teacher.activity.TeacherEventDetailsActivity;
import com.ssyc.gsk_teacher.adapter.EventAdapter;
import com.ssyc.gsk_teacher.bean.EventInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 全部活动Fragment
 * Created by Administrator on 2018/1/18 0018.
 */

public class TeacherAllEventFragment extends LazyBaseFragment implements SrfManager.OnPullRefreshListener, OnloadingMoreListener {

    //下拉刷新
    private SmartRefreshLayout srl;

    //列表控件
    private RecyclerView rv;

    //加载框
    private RelativeLayout rlLoading;

    //内容视图
    private RelativeLayout rlContent;

    //数据集合
    private List<EventInfo.ListBean> oldDatas;

    //空视图
    private View emptyView;

    //单例模式
    private static volatile TeacherAllEventFragment teacherEventFragment;

    //数据适配器
    private EventAdapter adapter;

    //分页加载
    private int page = 1;


    //单体模式
    private static class LazyHolder {
        private static final TeacherAllEventFragment INSTANCE = new TeacherAllEventFragment();
    }

    public static final TeacherAllEventFragment newInstance() {
        return TeacherAllEventFragment.LazyHolder.INSTANCE;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_teacher_event;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    private Handler handler = new Handler();

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        showContent();

        //初始化视图
        initView(view);

        //初始化下拉刷新
        initSrf();

        //初始化列表
        initRv();

        //获取数据
        http(BqaManager.NORML);
    }


    /**
     * 初始化视图
     */
    private void initView(View view) {
        srl = view.findViewById(R.id.srf);
        rv = view.findViewById(R.id.rv);
        rlLoading = view.findViewById(R.id.rl_loading);
        rlContent = view.findViewById(R.id.rl_content);
        rlLoading.setVisibility(View.VISIBLE);
        rlContent.setVisibility(View.GONE);
    }

    /**
     * 设置监听
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srl, this);
    }

    /**
     * 设置列表数据
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(getContext(), R.layout.base_rv_common_empty_view_white_bg, null);
        TextView tvMessage = emptyView.findViewById(R.id.tv_content);
        tvMessage.setText("您还未发布活动");
        adapter = new EventAdapter(getContext(), R.layout.teacher_rv_event, oldDatas);
        //条目长按事件
        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                    AlertDialogUtil.showAlertDialog(getContext(), "确定删除该条活动吗?", new AlertDialogUtil.onClickListener() {
                        @Override
                        public void onClickOk() {
                            doDeletEvent(position);
                        }
                    });

                return false;
            }
        });

        //条目点击事件
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //整体条目的点击事件
                // 跳转到活动详情界面
                Intent intent = new Intent(getContext(), TeacherEventDetailsActivity.class);
                intent.putExtra("data", oldDatas.get(position));
                startActivity(intent);
            }
        });
    }


    /**
     * 删除已结束的活动的方法
     */
    private void doDeletEvent(int position) {
        CustomDialogManager.show(getContext(), "删除中...");
        //删除的操作
        Map<String, String> map = new HashMap<>();

        map.put("type", "12");

        map.put("acc", AccountUtils.getAccount(BaseApplication.context));

        map.put("role",  AccountUtils.getRole(BaseApplication.context));

        map.put("rowid", oldDatas.get(position).getRowId() + "");

        HttpUtils.post(HttpAdress.DELETEEVENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast("服务器异常,上传失败", false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!android.text.TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("删除成功", false);
                            //删除该条记录,刷新界面
                            oldDatas.remove(position);
                            adapter.notifyDataSetChanged();
                        } else {
                            UiUtils.Toast("删除失败,返回异常码是:" + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 请求数据
     *
     * @param method
     */
    private void http(int method) {
        if (method == BqaManager.NORML || method == BqaManager.PULLREFRESH) {
            page = 1;
        } else {
            page++;
        }
        Map<String, String> map = new HashMap<>();
        map.put("type", "4");
        map.put("headmaster", "");
        map.put("acc", AccountUtils.getAccount(getContext()));
        map.put("role", AccountUtils.getRole(getContext()));
        map.put("page", page + "");
        HttpUtils.post(HttpAdress.ALLEVENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoading, srl, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }
                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    EventInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, EventInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            List<EventInfo.ListBean> newDatas = info.getList();
                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {
                                    oldDatas.clear();
                                    oldDatas.addAll(newDatas);
                                    BqaManager.setRv(emptyView, getContext(), adapter, rv, TeacherAllEventFragment.this);
                                } else {
                                    //更新数据
                                    BqaManager.updateRvBySmf(method, srl, rv, oldDatas, newDatas, adapter);
                                }
                            }
                        } else {
                            UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }

                    } else {
                        Log.i("test", Constants.EMPTY);
                    }

                } else {
                    Log.i("test", Constants.EMPTY);
                }

            }
        });
    }

    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        http(BqaManager.PULLREFRESH);
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        http(BqaManager.LOADINDGMORE);
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        //刷新数据
        if (busInfo != null && busInfo.getType() == TeacherEventActivity.UPDATASCORE) {
            http(BqaManager.PULLREFRESH);
        }

    }
}
